// pages/user/myShop/myShop.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    titleArr: [{ 'tit': '店铺名称：' }, { 'tit': '联系人：' }, { 'tit': '电话：' }, { 'tit': '地址：' }],
    //productArr: [{ 'tit': '测试一' }, { 'tit': '测试二' }, { 'tit': '测试三' }, { 'tit': '测试四' }, { 'tit': '测试五' }],
    productArr: [{ 'goods_id': '', 'img': '' }, { 'goods_id': '', 'img': '' }],
    isAgree:false,//是否同意规则
    postData:{},//请求数据
    shopImg:[],
    licenseImg:[],
  }, 

  //规则点击
  rulesClick: function () {
    console.log('规则点击');
    wx.navigateTo({
      url: '../../rules/rules',
    })
  },


  //选择商铺头像
  chooseIcon:function(){
    var that = this;
    wx.chooseImage({
      success: function (res) {
        console.log(res.tempFilePaths);
        var nshopImg = new Array();
        nshopImg[0] = res.tempFilePaths[0];
        that.setData({
          shopImg: nshopImg,
        })
        wx.showLoading({
          title: '正在上传图片',
        })
        that.uploadimg({
          url: app.globalData.requestURL + 'file/uploadImg',
          path: that.data.shopImg,
          oldName: that.data.postData.shop_img ? that.data.postData.shop_img:'',
          tit:'shop_img',
        })
      },
    })
  },


  //上传营业执照
  chooseLicenec:function(){
    var that = this;
    wx.chooseImage({
      success: function(res) {
        console.log(res.tempFilePaths);
        var nlicenseImg = new Array();
        nlicenseImg[0] = res.tempFilePaths[0];
        that.setData({
          licenseImg: nlicenseImg,
        })
        wx.showLoading({
          title: '正在上传图片',
        })
        that.uploadimg({
          url: app.globalData.requestURL + 'file/uploadImg',
          path: that.data.licenseImg,
          oldName: that.data.postData.license ? that.data.postData.license : '',
          tit: 'license',
        })
      },
    })
  },

  /*
      wx.chooseLocation({
      success: function(res) {
        console.log(res.name);
        console.log(res.address);
        data['shop_addr'] = res.address;
        data['longitude'] = res.longitude;
        data['latitude'] = res.latitude;
        that.setData({
            postData: data,
        })
      },
    })
  */

  //选择地址
  chooseAddress:function(){
    var that = this;
    var data = that.data.postData;
    wx.chooseLocation({
      success: function (res) {
        console.log(res.name);
        console.log(res.address);
        data['shop_addr'] = res.address;
        data['longitude'] = res.longitude;
        data['latitude'] = res.latitude;
        that.setData({
          postData: data,
        })
      },
    })
  },

  //是否同意规则
  rulesAgree:function(){
    var that = this;
    that.setData({
      isAgree: !that.data.isAgree,
    })

  },
  //输入信息
  messageInput:function(e){

    var that = this;
    var data = that.data.postData;
    if(e.currentTarget.id == 0){
      console.log('店铺名称');
      data['shop_name'] = e.detail.value;
    } else if (e.currentTarget.id == 1){
      console.log('联系人');
      data['contact_name'] = e.detail.value;
    }else{
      console.log('电话');
      data['contact_tel'] = e.detail.value;
    }
    that.setData({
      postData: data,
    })
  },
  //输入简介
  describeInput:function(e){
    var that = this;
    var data = that.data.postData;
    data['shop_introduce'] = e.detail.value;
    that.setData({
      postData: data,
    })
  },

  addBtnClick:function(){
    var that = this;
    console.log('添加点击');
    that.data.productArr.push({ 'goods_id': '', 'img': '' });
    var updateProductArr = that.data.productArr;
    that.setData({
      productArr: updateProductArr,
    })
  },

  //选择主营业务
  chooseType:function(){
    wx.navigateTo({
      url: '../timberType/timberType',
    })
  },

  //编辑产品
  editProduct:function(e){
    console.log(e.currentTarget.dataset.target);
    console.log(e.currentTarget.id);
    wx.navigateTo({
      url: '../editProduct/editProduct?tit=' + e.currentTarget.id + '&target=' + e.currentTarget.dataset.target + '&goods_id=' + e.currentTarget.dataset.goods_id,
    })
  },

  //发布按钮点击
  pushClick:function(){
    var that = this;
    if (that.data.isAgree) {
      if (that.data.postData.shop_img.length == 0 || that.data.postData.license.length == 0) {
        wx.showToast({
          title: '请上传店铺图片或者营业执照',
          icon: 'none'
        })
      } else {
        that.requestData();//上传数据
      }
    } else {
      wx.showToast({
        title: '请先阅读并同意相关条款',
        icon: 'none'
      })
    }
  },

  //多张图片上传
  uploadimg: function (data) {
    console.log('------------');
    console.log(data.path);
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      header: {
        compress: '0',
        height: '108',
        width: '100',
        imgName:data.oldName,
      },
      name: 'fileData',
      formData: null,
      success: (resp) => {
        success++;
        console.log(resp.data)
        console.log(i);
        var result = JSON.parse(resp.data);
        if (result.code == 0) {
          var ndata = that.data.postData;
          if (data.tit == 'shop_img'){
            ndata['shop_img'] = result.resultData;
          }else{
            ndata['license'] = result.resultData;
          }
          that.setData({
            postData: ndata,
          })
        }
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        console.log(i);
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用   
          console.log('执行完毕');
          wx.hideLoading();
          console.log('成功：' + success + " 失败：" + fail);
        } else {//若图片还没有传完，则继续调用函数
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },

  //请求数据
  requestData: function () {
    var that = this;
    var data = that.data.postData;
    var goods_ids = new Array();
    //获得 goods_ids数组
    for (var i = 0; i < that.data.productArr.length;i++){
      goods_ids.push(that.data.productArr[i].goods_id);
    }
    data['goods_ids'] = goods_ids.join(",");
    data['openId'] = wx.getStorageSync('userInfo').userId;
    that.setData({
      postData: data,
    })

    app.post('shop/saveOrUpdateShopMsg', that.data.postData).then((res) => {
      console.log('success');
      console.log(res);
      if (res.code == 0) {
        var userInfo = wx.getStorageSync('userInfo');
        userInfo['isShopMsg'] = 0;
        wx.setStorageSync('userInfo', userInfo);
        wx.navigateBack();//返回上一页
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false,
        })
      }
    }).catch((errMsg) => {
      console.log('fail');
      console.log(errMsg + '失败');
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 判断是否有店铺 有店铺请求店铺信息
    if (wx.getStorageSync('userInfo').isShopMsg == 0){
      app.post('shop/queryShopInfo', { openId: wx.getStorageSync('userInfo').userId}).then((res) => {
        console.log('success');
        console.log(res);
        if (res.code == 0) {
          var pdata = that.data.postData;
          pdata['shop_name'] = res.resultData.shopInfo.shop_name;
          pdata['contact_name'] = res.resultData.shopInfo.contact_name;
          pdata['contact_tel'] = res.resultData.shopInfo.contact_tel;
          pdata['shop_addr'] = res.resultData.shopInfo.shop_addr;
          pdata['latitude'] = res.resultData.shopInfo.latitude;
          pdata['longitude'] = res.resultData.shopInfo.longitude;
          pdata['variety'] = res.resultData.shopInfo.variety;
          pdata['shop_introduce'] = res.resultData.shopInfo.shop_introduce;
          pdata['shop_img'] = res.resultData.shopInfo.shop_img;
          pdata['license'] = res.resultData.shopInfo.license;
        
          //需要显示的图片的地址
          var nshopImg = new Array();
          var nlicenseImg = new Array();
          nshopImg[0] = app.globalData.requestURL + 'upload/' + res.resultData.shopInfo.shop_img;
          nlicenseImg[0] = app.globalData.requestURL + 'upload/' + res.resultData.shopInfo.license;

          var nproductArr = new Array();
          for (var i = 0; i < res.resultData.produces.length;i++){
            console.log(res.resultData.produces[i].id)
            console.log(res.resultData.produces[i].pro_img.split(",")[0])
            var part ={};
            part.goods_id = res.resultData.produces[i].id;
            part.img = app.globalData.requestURL + 'upload/' + res.resultData.produces[i].pro_img.split(",")[0];
            nproductArr.push(part);
          }

          that.setData({
            postData: pdata,
            productArr: nproductArr,
            shopImg: nshopImg,
            licenseImg: nlicenseImg,
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: res.msg,
            showCancel: false,
          })
        }
      }).catch((errMsg) => {
        console.log('fail');
        console.log(errMsg + '失败');
      })
    }
  
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})